﻿<!DOCTYPE html>
<html>
<head>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <title>太好了</title>
    <style type="text/css" media="all">
        #log {color: blue;border: #ccc 1px dotted;width: 100%;height: 400px;overflow-y: scroll;font-size: 16px;}
        #text {width: 500px;}
    </style>
</head>
<body>
<h3><span id="real_time"></span> sprint boot mybatis学习</h3>
<h3>
    <a href="pages/city/admin.html" target="_blank">城市资料管理</a>
</h3>
<div>
    toCid: <input id="toCid" value="0"/>, text: <input id="text" value='{"action": "getOne", "message": "太好了"}'/>
    <input type="button" onclick="sendToCid();" value="sendToCid()"/>
    <input type="button" onclick="$('#log').val('');" value="clearLog"/>
</div>
<textarea id="log">log</textarea>
</body>
</html>
<script src="js/jquery.3.2.1.min.js"></script>
<script src="js/common.js"></script>
<script>
    //alert(location.href);
    var cid = '0'; //用户在多个地方登录的时候能够同时接收到消息
    //alert(conf.websocketBase);
    var websocketUrl = `${conf.websocketBase}${cid}`;//conf.websocketBase可以直接在这里写，比如【ws://localhost:8886/websocket/】
    //alert(websocketUrl);
    $(`#log`).html(`${getNowTime()}: cid = ${cid}, websocketBase = ${conf.websocketBase}, websocketUrl = ${websocketUrl}`);
    var lockReconnect = false; //避免websocket重复连接
    var websocket = null;
    //心跳检测
    var heartCheck = {
        timeout: 540000, //9分钟发一次心跳
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                //onmessage拿到返回的心跳就说明连接正常
                websocket.send("ping");
                appendMessage("ping");
                self.serverTimeoutObj = setTimeout(function () {
                    //如果超过一定时间还没重置，说明后端主动断开了
                    //如果onclose会执行reconnect，我们执行websocket.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    websocket.close();
                }, self.timeout)
            }, this.timeout)
        }
    }

    function createWebSocket(url) {
        try {
            if ('WebSocket' in window) {
                websocket = new WebSocket(url);
            } else if ('MozWebSocket' in window) {
                websocket = new MozWebSocket(url);
            } else {
                alert("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器，请勿使用IE10以下浏览器，360浏览器请使用极速模式，不要使用兼容模式！");
            }
            initEventHandle();
        } catch (e) {
            reconnect(url);
            console.log(e);
        }
    }

    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    function reconnect(url) {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () { //没连接上会一直重连，设置延迟避免请求过多
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }

    //将消息显示在网页上
    function appendMessage(message) {
        $('#log').val($('#log').val() + '\n' + getNowTime() + ": " + message);
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    // 把JSON发送到指定的客户端
    function sendTo(toCid, json) {
        json.cid = cid;
        json.toCid = toCid;
        websocket.send(JSON.stringify(json));
    }
    //测试发送消息
    function sendToCid() {
        var data = JSON.parse($('#text').val());
        sendTo($('#toCid').val(), data);
        $('#text').focus();
    }

    function sendToServer() {
        var data = JSON.parse($('#text').val());
        websocket.send(JSON.stringify(data));
        $('#text').focus();
    }
    function reload() {
        setTimeout(function () {
            location.reload();
        }, 2000);
    }

    // 初始化处理
    function initEventHandle() {
        websocket.onclose = function () {
            reconnect(websocketUrl);
            appendMessage("连接关闭!");
            reload();
        };
        websocket.onerror = function () {
            reconnect(websocketUrl);
            appendMessage("WebSocket连接错误!");
            reload();
        };
        websocket.onopen = function () {
            heartCheck.reset().start(); //心跳检测重置
            //一打开就ping何太军
            // websocket.send(JSON.stringify(ping));
            onopenHandler();
        };
        websocket.onmessage = function (event) {
            //公共操作开始
            //如果获取到消息，心跳检测重置，因为拿到任何消息都说明当前连接是正常的
            heartCheck.reset().start();
            //alert(event.data);
            //var json = JSON.parse(event.data);
            onmessageHandler(event.data);
        };
    }

    // 建立WebSocket连接
    createWebSocket(websocketUrl);

    // 由各个子系统重写onopen()方法
    function onopenHandler() {
        appendMessage(`websocket打开`);
    }

    // 由各个子系统重写onmessage()方法
    function onmessageHandler(data) {
        appendMessage(data);
        var json = JSON.parse(data);
        if (json) {
            var action = json.action;
            if (action != null && action != '' && action == 'reloadConfig') {
                reloadConfig();
            }
        } else {
            appendMessage("不能识别的消息：" + data);
        }
    }

    // 显示时间
    setInterval("showTime()", 1000);
    function showTime() {
        document.getElementById("real_time").innerText = getNowTime();
    }
</script>